from PyQt5.QtWidgets import QDialog, QComboBox, QLineEdit, QFormLayout, QDialogButtonBox, QVBoxLayout, QMessageBox, QStyledItemDelegate


class ComboBoxDelegate(QStyledItemDelegate):
    '''
    设置下拉框每行的高度
    '''
    def __init__(self, parent=None):
        super().__init__(parent)

    def sizeHint(self, option, index):
        size = super().sizeHint(option, index)
        size.setHeight(40)  # 设置行高为40，调整你想要的行高
        return size



class EditStoreDialog(QDialog):
    def __init__(self, db,store_names, local_data,parent=None):
        super().__init__(parent)
        self.db = db
        self.setWindowTitle("店铺登录数据")
        self.setFixedSize(300, 250)

        # 居中显示
        if parent:
            parent_geometry = parent.geometry()
            x = parent_geometry.x() + (parent_geometry.width() - self.width()) // 2
            y = parent_geometry.y() + (parent_geometry.height() - self.height()) // 2
            self.setGeometry(x, y, self.width(), self.height())
            self.setStyleSheet(parent.styleSheet())

        # 获取所有店铺
        self.store_map = {row['store_name']: row for row in local_data}
        self.store_names = []

        # 下拉框选择店铺
        self.storeCombo = QComboBox(self)
        self.storeCombo.setItemDelegate(ComboBoxDelegate())  # 设置下拉项行高
        # 将店铺信息填充到下拉框
        for store in store_names:
            if store[1] == '拼多多':
                store_info = f"{store[2]}"
                self.storeCombo.addItem(store_info, store[0])  # 第二个参数是店铺的 id
                self.store_names.append(store_info)

        self.storeCombo.setCurrentIndex(0)
        self.storeCombo.currentTextChanged.connect(self.load_store_info)

        # 表单控件
        self.storeNameEdit = QLineEdit(self)
        self.storeNameEdit.setVisible(False)
        self.storeNameEdit.setReadOnly(True)

        self.usernameEdit = QLineEdit(self)
        self.passwordEdit = QLineEdit(self)

        # 表单布局
        formLayout = QFormLayout()
        formLayout.addRow("选择店铺:", self.storeCombo)
        formLayout.addRow("", self.storeNameEdit)
        formLayout.addRow("用户名:", self.usernameEdit)
        formLayout.addRow("密码:", self.passwordEdit)

        # 按钮区
        buttonBox = QDialogButtonBox(self)
        saveButton = buttonBox.addButton("💾 保存", QDialogButtonBox.AcceptRole)
        cancelButton = buttonBox.addButton("📛 取消", QDialogButtonBox.RejectRole)
        deleteButton = buttonBox.addButton("❌ 删除", QDialogButtonBox.DestructiveRole)

        saveButton.clicked.connect(self.saveStore)
        cancelButton.clicked.connect(self.reject)
        deleteButton.clicked.connect(self.deleteStore)

        # 总体布局
        layout = QVBoxLayout()
        layout.addLayout(formLayout)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

        # 初始加载第一个店铺信息
        if self.store_map:
            self.load_store_info(self.store_names[0])
    def load_store_info(self, store_name):
        store_info = self.store_map.get(store_name, {})
        self.storeNameEdit.setText(store_info.get('store_name', ''))
        self.usernameEdit.setText(store_info.get('username', ''))
        self.passwordEdit.setText(store_info.get('password', ''))

    def saveStore(self):
        store_name = self.storeCombo.currentText()
        username = self.usernameEdit.text()
        password = self.passwordEdit.text()

        if store_name:
            self.db.insert_or_update_store(store_name, username, password)
            # self.accept()
            QMessageBox.information(self, '成功', '店铺登录信息保存成功')
        else:
            QMessageBox.warning(self, '警告', '请填写完整的店铺信息')

    def deleteStore(self):
        store_name = self.storeCombo.currentText()

        msg = QMessageBox(self)
        msg.setWindowTitle("确认删除")
        msg.setText(f'确定要删除店铺 "{store_name}" 吗？此操作不可恢复。')

        yes_btn = msg.addButton("是", QMessageBox.YesRole)
        no_btn = msg.addButton("否", QMessageBox.NoRole)
        msg.exec_()

        if msg.clickedButton() == yes_btn:
            self.db.delete_store(store_name)
            self.accept()